<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./lib/bootstrap.css">
</head>

<body>
  <!-- 文件框 -->
  <input type="file" name="" id="file">
  <!-- 上传按钮 -->
  <button>上传</button>

  <!-- bootstrap 中的进度条 -->
  <div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
      0%
    </div>
  </div>
  <img src="" alt="" width="800">
  <script>
    const btn = document.querySelector('button')
    btn.addEventListener('click', function () {
      const files = document.querySelector('#file').files
      if (files.length <= 0) {
        return alert('请选择要上传的文件！')
      }
      const fd = new FormData()
      // 将用户选择的文件，添加到 FormData 中
      fd.append('avatar', files[0])
      const xhr = new XMLHttpRequest()
      //计算文件上传的进度
      xhr.upload.addEventListener('progress', e => {
        if (e.lengthComputable) {
          let procentComplete = Math.ceil((e.loaded / e.total) * 100)
          document.querySelector('#percent').style.width = procentComplete + '%'
          document.querySelector('#percent').innerHTML = procentComplete + '%'
        }

      })
      xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
      xhr.send(fd)
      xhr.addEventListener('readystatechange', function () {

        if (this.readyState === 4 && this.status === 200) {
          //获取服务器响应数据
          const data = JSON.parse(this.responseText)

          // console.log(data)
          if (data.status === 200) {
            // 上传成功
            document.querySelector('img').src = 'http://www.liulongbin.top:3006' + data.url
          } else {
            // 上传失败
            console.log('图片上传失败！' + data.message)
          }
        }
      })
    })
  </script>
</body>

</html>